//
//  LSZDetailsProblemVC.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/9/4.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZDetailsProblemVC.h"

@interface LSZDetailsProblemVC ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property(nonatomic,strong) NSMutableArray * arrayData;
@property(nonatomic,strong) UITableView * tableViewQuestionerDetails;
@property(nonatomic,strong) UIView * viewLow;
@property(nonatomic,strong) UITextView * textView;
@property(nonatomic,strong) UIButton * button;
@end

@implementation LSZDetailsProblemVC
-(void)initWithGetData
{
    [LSZRequestDicData initWithDetailInterface:self.id_id :^(BOOL isOk, NSString * string, LSZQuestionParticipantDetailsInterfaceManager * manager) {
        if (isOk == YES) {
            self.arrayData = manager.mutMgArray;
            [self.tableViewQuestionerDetails reloadData];
        }else{
            if ([string isEqualToString:@"重复登录"]) {
                [LSZPublicClassDataToll RepeatLoginInterfaceJump:self.view fromVC:@"LSZDetailsProblemVC"];
            }else{
                [LSZPublicClassDataToll initWithAlertKuangView:self.view string:string];
            }
        }
    }];
}
-(void)goToLogin
{
    [LSZPublicClassDataToll goToLogin];
}
-(void)addNotificationCenter
{
    NSString * strDelete = [NSString stringWithFormat:@"%@Login",@"LSZDetailsProblemVC"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToLogin) name:strDelete object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"互助详情";
    [self addNotificationCenter];
    self.arrayData = [[NSMutableArray alloc]init];
    [self initWithGetData];
    [self.tableViewQuestionerDetails registerClass:[LSZProblemContentTableViewCell class] forCellReuseIdentifier:@"LSZProblemContentTableViewCell"];
    [self.tableViewQuestionerDetails registerClass:[LSZSupportHeadCell class] forHeaderFooterViewReuseIdentifier:@"LSZSupportHeadCell"];
    [self.tableViewQuestionerDetails registerClass:[LSZMainProblemTableViewCell class] forCellReuseIdentifier:@"LSZMainProblemTableViewCell"];
    [LSZSpecialPackaging initWithAppraise:self.view :^(UIView * viewLow, UITextView * textView, UIButton * button) {
        self.viewLow = viewLow;
        self.textView = textView;
        self.textView.delegate = self;
        self.button = button;
        [self.button addTarget:self action:@selector(clickSend) forControlEvents:UIControlEventTouchUpInside];
    }];
    [self addDelete];
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowDetails:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideDetails:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(judgeByCurrentStatus)];
    [self.view addGestureRecognizer:tapGesture];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.arrayData.count > 0) {
        return 2;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.arrayData.count;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CGFloat height = [LSZSpecialPackaging getHeightOfText:ScreenWidth-80 height:ScreenHeight font:15 :self.mutualProblemMg.content];
        if (self.mutualProblemMg.headUrlArray.count >0) {
            return 60+height+80;
        }else{
            return 60+height;
        }
    }else{
        LSZQuestionParticipantDetailsInterfaceMg * mg = nil;
        mg = self.arrayData[indexPath.row];
        CGFloat height = [LSZSpecialPackaging getHeightOfText:ScreenWidth-80 height:ScreenHeight font:15 :mg.content];
        return 60+height;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.00001;
    }else{
        return 40;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }else{
        return 0.0001;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cellHeader"];
        if (!cell) {
            cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"cellHeader"];
        }
        return cell;
    }else{
        LSZSupportHeadCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZSupportHeadCell"];
        if (!cell) {
            cell = [[LSZSupportHeadCell alloc]initWithReuseIdentifier:@"LSZSupportHeadCell"];
        }
        if (self.arrayData.count >0) {
            cell.labelTitle.text = [NSString stringWithFormat:@"%lu条回答",(unsigned long)(long)self.arrayData.count];
            cell.labelTitle.hidden = NO;
        }else{
            cell.labelTitle.hidden = YES;
        }
        return cell;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        LSZMainProblemTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZMainProblemTableViewCell" forIndexPath:indexPath];
        cell.MutualProblemMg = self.mutualProblemMg;
        if ([[_MyCenter my_id] isEqualToString:@""]) {
            [LSZRequestData initWithPersonalCenter:^(BOOL ISoK, NSString * str, NSDictionary * dic) {
                [self initWithCell:cell];
            }];
        }else{
            [self initWithCell:cell];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        LSZProblemContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZProblemContentTableViewCell" forIndexPath:indexPath];
        LSZQuestionParticipantDetailsInterfaceMg * mg = nil;
        mg = self.arrayData[indexPath.row];
        cell.QuestionParticipantDetailsInterfaceMg = mg;
        cell.butState.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}
-(void)initWithCell :(LSZMainProblemTableViewCell *)cell
{
    NSLog(@"%@",[_MyCenter my_id]);
    if ([self.mutualProblemMg.customer_id isEqualToString:[_MyCenter my_id]]) {
        cell.butState.hidden = NO;
    }else{
        cell.butState.hidden = YES;
    }
    if ([self.mutualProblemMg.solved isEqualToString:@"false"]) {
        [cell.butState setTitle:@"已解决" forState:UIControlStateNormal];
        cell.butState.userInteractionEnabled = YES;
        cell.butState.backgroundColor = themeColor;
        [cell.butState setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cell.butState addTarget:self action:@selector(clickButState) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [cell.butState setTitle:@"已解决" forState:UIControlStateNormal];
        cell.butState.userInteractionEnabled = NO;
        cell.butState.backgroundColor = [UIColor whiteColor];
        [cell.butState setTitleColor:themeColor forState:UIControlStateNormal];
    }
}
#pragma mark - 点击已解决
-(void)clickButState
{
    [LSZRequestData theProblemMutualAssistanceBecomeSolved:self.id_id :^(BOOL isOk, NSString * string, NSString * str) {
        if (isOk == YES) {
            LSZProblemContentTableViewCell * cell = (LSZProblemContentTableViewCell *)[self.tableViewQuestionerDetails cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
            [cell.butState setTitle:@"已解决" forState:UIControlStateNormal];
            cell.butState.userInteractionEnabled = NO;
            cell.butState.backgroundColor = [UIColor whiteColor];
            [cell.butState setTitleColor:themeColor forState:UIControlStateNormal];
            NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"2",@"state",@(self.numRow),@"number",@(self.chooseWhat),@"chooseWhat", nil];
            NSNotification *notification =[NSNotification notificationWithName:@"mutualAid" object:nil userInfo:dic];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
        }else{
            [self initWithtring:str];
        }
    }];
}
#pragma mark - 判断是否添加导航删除
-(void)addDelete
{
    if ([[_MyCenter my_id] isEqualToString:@""]) {
        [LSZRequestData initWithPersonalCenter:^(BOOL ISoK, NSString * str, NSDictionary * dic) {
            [self addDeteleUI];
        }];
    }else{
        [self addDeteleUI];
    }
}
-(void)addDeteleUI
{
    if ([self.mutualProblemMg.customer_id isEqualToString:[_MyCenter my_id]]) {
        UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(clickDeleteRelease)];
        self.navigationItem.rightBarButtonItem = rightBarItem;
    }
}
#pragma mark - 删除发布信息
-(void)clickDeleteRelease
{
    [LSZRequestData mutualDeletionTheirOwnIssues:self.id_id :^(BOOL isOk, NSString * str, NSString * string) {
        if (isOk == YES) {
            [self initWithtring:@"删除成功!"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"state",@(self.numRow),@"number",@(self.chooseWhat),@"chooseWhat", nil];
                NSNotification *notification =[NSNotification notificationWithName:@"mutualAid" object:nil userInfo:dic];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                [[NSNotificationCenter defaultCenter] removeObserver:self];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [self initWithtring:str];
        }
    }];
}
#pragma mark - 点击发送按钮需要监控键盘的上升和下落
-(void)clickSend
{
    if (self.textView.text.length >0) {
        [self.view endEditing:YES];
        [LSZRequestData initWithAnswerQuestions:self.id_id content:self.textView.text :^(BOOL isOk, NSString * string, NSDictionary * dic) {
            if (isOk == YES) {
                self.textView.text = @"";
                [self initWithtring:@"提交成功!"];
                [self initWithGetData];
                [self keyboardWhereabouts];
            }else{
                [self initWithtring:string];
            }
        }];
    }else{
        [self initWithtring:@"内容不能为空!"];
    }
}
//当键盘出现或改变时调用
- (void)keyboardWillShowDetails:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    
    CGRect frame = self.viewLow.frame;
    frame.origin.y = ScreenHeight-self.viewLow.frame.size.height-height-HOME_INDICATOR_HEIGHT;
    self.viewLow.frame = frame;
    
    CGRect frameTab = self.tableViewQuestionerDetails.frame;
    frameTab.size.height =  ScreenHeight-self.viewLow.frame.size.height-height-HOME_INDICATOR_HEIGHT;
    self.tableViewQuestionerDetails.frame = frameTab;
    
    [UIView commitAnimations];
}
//当键退出时调用
- (void)keyboardWillHideDetails:(NSNotification *)aNotification{
    [self keyboardWhereabouts];
}
-(void)keyboardWhereabouts
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
 
    CGRect frame = self.viewLow.frame;
    frame.origin.y =  ScreenHeight-self.viewLow.frame.size.height-HOME_INDICATOR_HEIGHT;
    self.viewLow.frame = frame;
    
    CGRect frameTab = self.tableViewQuestionerDetails.frame;
    frameTab.size.height =  ScreenHeight-self.viewLow.frame.size.height-HOME_INDICATOR_HEIGHT;
    self.tableViewQuestionerDetails.frame = frameTab;
    
    [self clickSingleDynamic];
    [UIView commitAnimations];
}
#pragma mark - 判断键盘的状态
-(void)judgeByCurrentStatus
{
    if(self.tableViewQuestionerDetails.frame.size.height < ScreenHeight- self.viewLow.frame.size.height){
        [self keyboardWhereabouts];
    }
}
#pragma mark - 输入框的代理方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self clickSend];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}
-(void)clickSingleDynamic
{
    [self.view endEditing:YES];
}
-(UITableView *)tableViewQuestionerDetails
{
    if (_tableViewQuestionerDetails == nil) {
        _tableViewQuestionerDetails = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , [[UIScreen mainScreen] bounds].size.height-60-HOME_INDICATOR_HEIGHT) style:UITableViewStylePlain];
        _tableViewQuestionerDetails.delegate = self;
        _tableViewQuestionerDetails.dataSource = self;
        _tableViewQuestionerDetails.estimatedRowHeight=0;
        _tableViewQuestionerDetails.estimatedSectionFooterHeight =0;
        _tableViewQuestionerDetails.estimatedSectionHeaderHeight =0;
        [_tableViewQuestionerDetails setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
        [self.view addSubview:_tableViewQuestionerDetails];
    }
    return _tableViewQuestionerDetails;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
